package top.saplf.sileny.reader.shelf

import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.jakewharton.rxbinding2.view.RxView
import io.realm.Realm
import io.realm.RealmList
import kotlinx.android.synthetic.main.activity_reader_page.*
import me.eugeniomarletti.extras.bundle.BundleExtra
import me.eugeniomarletti.extras.bundle.base.Boolean
import me.eugeniomarletti.extras.intent.IntentExtra
import me.eugeniomarletti.extras.intent.base.String
import top.saplf.sileny.R
import top.saplf.sileny.base.ui.IActivity
import top.saplf.sileny.ext.slideDownAppear
import java.util.*

/**
 * @author saplf
 */
class ReaderPageActivity : AppCompatActivity(), IActivity {

    companion object {
        var Intent.bookId: String by IntentExtra.String("")
        var Bundle.settingShow: Boolean by BundleExtra.Boolean(defaultValue = false)
    }

    private var mSettingShow: Boolean = false
        set(value) {
            field = value
            settingPanel.slideDownAppear(value)
            if (!value) {
                if (typesetPanel.visibility == View.VISIBLE) {
                    typesetPanel.slideDownAppear(false) {
                        typesetPanel.visibility = View.GONE
                    }
                }
                if (bookMarkPanel.visibility == View.VISIBLE) {
                    bookMarkPanel.slideDownAppear(false) {
                        bookMarkPanel.visibility = View.GONE
                    }
                }
            }
            rootLayout.systemUiVisibility = if (value) View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN else View.SYSTEM_UI_FLAG_FULLSCREEN
        }
    private val mRealm: Realm by lazy { Realm.getDefaultInstance() }
    private val mBook: LocalBook by lazy {
        mRealm.where(LocalBook::class.java)
                .equalTo("id", intent.bookId)
                .findFirst()
    }

    override fun onLayoutRes(): Int = R.layout.activity_reader_page

    private val bookMarkAdapter: BookMarkAdapter
            by lazy {
                BookMarkAdapter().apply {
                    deleteAction = {
                        mRealm.beginTransaction()
                        val result = mBook.bookMarks?.remove(it)
                        mRealm.commitTransaction()
                        result ?: false
                    }
                    itemAction = {
                        textPaper.jumpTo(it.seek)
                        mSettingShow = false
                    }
                    addData(mBook.bookMarks ?: emptyList())
                }
            }

    override fun onViewCreated(savedInstanceState: Bundle?) {
        textPaper.currentPageSeek = mBook.seek
        textPaper.pointerChangeAction = {
            mRealm.beginTransaction()
            mBook.seek = it
            mRealm.commitTransaction()
        }
        textPaper.fileUrl = mBook.path
        RxView.clicks(textPaper)
                .subscribe({
                    mSettingShow = !mSettingShow
                }, { it.printStackTrace() })
        RxView.clicks(nextPage)
                .subscribe({
                    if (mSettingShow) {
                        mSettingShow = !mSettingShow
                    } else {
                        val success = textPaper.nextPage()
                        if (!success) {
                        }//todo if failed
                    }
                }, { it.printStackTrace() })
        RxView.clicks(previewPage)
                .subscribe {
                    if (mSettingShow) {
                        mSettingShow = !mSettingShow
                    } else {
                        textPaper.prevPage()
                    }
                }
        RxView.clicks(typesetBtn)
                .subscribe {
                    settingPanel.slideDownAppear(false) {
                        settingPanel.alpha = 0f
                        typesetPanel.visibility = View.VISIBLE
                        typesetPanel.alpha = 0f // 防止闪屏
                        typesetPanel.slideDownAppear(true)
                    }
                }
        RxView.clicks(smallerBtn)
                .subscribe {
                    textPaper.decSize()
                }
        RxView.clicks(biggerBtn)
                .subscribe {
                    textPaper.accSize()
                }
        RxView.clicks(bookMarkBtn)
                .subscribe {
                    settingPanel.slideDownAppear(false) {
                        settingPanel.alpha = 0f
                        bookMarkPanel.visibility = View.VISIBLE
                        bookMarkPanel.alpha = 0f
                        bookMarkPanel.slideDownAppear(true)
                    }
                }
        RxView.clicks(addBookMarkBtn)
                .subscribe {
                    var bookMarks = mBook.bookMarks
                    if (bookMarks == null) {
                        bookMarks = RealmList()
                        mBook.bookMarks = bookMarks
                    }
                    mRealm.beginTransaction()
                    val element = BookMark(UUID.randomUUID().toString(), textPaper.currentPageSeek, textPaper.previewText())
                    bookMarks.add(element)
                    mRealm.commitTransaction()
                    bookMarkAdapter.addData(element)
                    mSettingShow = false
                }
        bookMarkList.layoutManager = LinearLayoutManager(this)
        bookMarkList.adapter = bookMarkAdapter

        if (savedInstanceState == null) {
            mSettingShow = false
        } else {
            mSettingShow = savedInstanceState.settingShow
        }
    }

    override fun onSaveInstanceState(outState: Bundle?) {
        super.onSaveInstanceState(outState)
        outState?.run {
            settingShow = mSettingShow
        }
    }

    override fun onResume() {
        super.onResume()
        if (mPaused) {
            mPaused = false
            mSettingShow = mSettingShow
        }
    }

    private var mPaused = false

    override fun onPause() {
        super.onPause()
        mPaused = true
    }

    override fun onDestroy() {
        super.onDestroy()
        mRealm.close()
        textPaper.close()
    }
}